<template>
  <div>
    <el-upload
      :disable="fileList.length===limit"
      :limit="limit"
      :action="action"
      list-type="picture-card"
      :headers="headers"
      :data="data"
      :on-exceed="handleExceed"
      :on-preview="handlePictureCardPreview"
      :on-success="handlerSuccess"
      :file-list="fileList"
      :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getImageUrl } from '@/utils'

export default {
  props: {
    limit: {
      type: Number
    },
    showList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    showList(lists) {
      // 用于重置上传列表
      if (lists && lists.length > 0) {
        lists.map(item => {
          const list = {
            id: item,
            status: 'success',
            // eslint-disable-next-line no-undef
            url: `${item}`
          }
          this.fileList.push(list)
        })
      } else {
        this.fileList = []
      }
    }
  },
  data() {
    return {
      fileList: [],
      headers: {
        token: getToken()
      },
      data: {
        prefixMenu: 'image'
      },
      dialogImageUrl: '',
      dialogVisible: false,
      // eslint-disable-next-line no-undef
      action: `${process.env.BASE_API}/base/attachment/upload`
    }
  },
  methods: {
    handleRemove(file, fileList) {
      const uploadList = fileList.map(item => {
        if (item.id) {
          return getImageUrl(item.id)
        } else {
          return getImageUrl(item.response.data.id)
        }
      })
      this.$emit('get-file-list', uploadList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handlerSuccess(response, file, fileList) {
      if (response.code === '200') {
        const uploadList = fileList.map(item => {
          if (item.id) {
            return getImageUrl(item.id)
          } else {
            return getImageUrl(item.response.data.id)
          }
        })
        this.$emit('get-file-list', uploadList)
      } else {
        this.fileList = []
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning('只能上传' + this.limit + '个文件')
    }
  }
}
</script>

<style scoped>

</style>
